package com.hbzhit.modules.sys.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hbzhit.common.enums.RoleOrgTypeEnum;
import com.hbzhit.modules.sys.dao.SysRoleOrgDao;
import com.hbzhit.modules.sys.entity.SysRoleOrgEntity;
import com.hbzhit.modules.sys.service.SysRoleOrgService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


/**
 * 角色与组织对应关系
 *
 * @author Mark sunlightcs@gmail.com
 */
@Service("sysRoleOrgService")
public class SysRoleOrgServiceImpl extends ServiceImpl<SysRoleOrgDao, SysRoleOrgEntity> implements SysRoleOrgService {

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void saveOrUpdate(Long roleId, Integer roleOrgType, List<Long> orgIdList) {
		// 删除角色与组织关系
		deleteBatch(new Long[]{roleId});
		// 非自定义组织数据
		if (roleOrgType != RoleOrgTypeEnum.CUSTOM.getValue()) {
			return;
		}
		// 集合为空
		if(CollUtil.isEmpty(orgIdList)) {
			return;
		}

		// 保存角色与组织关系
		List<SysRoleOrgEntity> list = new ArrayList<>();
		for(Long orgId : orgIdList){
			SysRoleOrgEntity sysRoleOrgEntity = new SysRoleOrgEntity();
			sysRoleOrgEntity.setOrgId(orgId);
			sysRoleOrgEntity.setRoleId(roleId);
			list.add(sysRoleOrgEntity);
		}
		if (CollectionUtil.isNotEmpty(list)) {
			this.saveBatch(list);
		}
	}

	@Override
	public List<Long> queryOrgIdList(Long roleId) {
		return baseMapper.queryOrgIdList(roleId);
	}

	@Override
	public void deleteBatch(Long[] roleIds) {
		this.remove(new LambdaQueryWrapper<SysRoleOrgEntity>().in(SysRoleOrgEntity::getRoleId, Arrays.asList(roleIds)));
	}

}
